package edu.spec.basic.service.impl;

import edu.spec.basic.dao.iface.ICommandDao;
import edu.spec.basic.dao.iface.IRoleCommandDao;
import edu.spec.basic.dao.iface.IRoleDao;
import edu.spec.basic.dao.iface.IUserRoleDao;
import edu.spec.basic.model.Command;
import edu.spec.basic.model.Role;
import edu.spec.basic.model.RoleCommand;
import edu.spec.basic.model.exception.SysException;
import edu.spec.basic.service.iface.IRoleService;
import org.madgecko.basic.model.Pager;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.List;

@Service
public class RoleService implements IRoleService {

    @Inject
    private IRoleDao roleDao;
	@Inject
	private ICommandDao commandDao;
	@Inject
	private IRoleCommandDao roleCommandDao;
	@Inject
	private IUserRoleDao userRoleDao;

    @Override
    public List<Role> listAllRole() {
        return roleDao.listAllRole();
    }

	@Override
	public List<Role> listRoleByUser(Integer userId) {
		return roleDao.listRoleByUser(userId);
	}

	@Override
	public Role load(int id) {
		return roleDao.load(id);
	}

	@Override
	public Role add(Role role) {
		return roleDao.add(role);
	}

	@Override
	public void delete(Integer id) {
		roleCommandDao.deleteByRole(id);
		userRoleDao.deleteByRole(id);
		roleDao.delete(id);
	}

	@Override
	public Role copyRole(Integer id) {
		Role dbRole = roleDao.load(id);
		if(dbRole == null){
			throw new SysException("要复制的角色[" + id + "]不存在");
		}
		Role copy = new Role();
		copy.setRoleName(dbRole.getRoleName());
		copy.setDes(dbRole.getDes());
		copy.setRoot(dbRole.getRoot());
		copy.setStatus(dbRole.getStatus());

		//TODO 提高性能是否修改为只要id
		roleDao.add(copy);
		//TODO 此时取不出id
		List<Command> commands =  commandDao.listCommandByRole(id);
		for(Command c : commands){
			RoleCommand rc = new RoleCommand();
			rc.setRole(copy);
			rc.setCommand(c);
			roleCommandDao.add(rc);
		}
		return copy;
	}

	@Override
	public void update(Role role) {
		roleDao.update(role);
	}

	@Override
	public Pager<Role> findRoleByCon(Integer status, String con) {
		return roleDao.findRoleByCon(status, con);
	}
}
